<template>
  <div class="promotion-container">
    <!-- 搜索栏 -->
    <div class="search-wrapper">
      <el-input
        v-model="searchText"
        placeholder="请输入生鲜名称搜索"
        style="width: 300px"
        clearable
        @keyup.enter="handleSearch">
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleSearch">
        <el-icon><Search /></el-icon>搜索
      </el-button>
      <el-button type="success" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增促销
      </el-button>
      <el-button type="warning" @click="handleSyncPrices">
        <el-icon><Refresh /></el-icon>同步价格
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="name" label="促销名称" min-width="150" align="center" />
      <el-table-column prop="productName" label="商品名称" min-width="120" align="center" />
      <el-table-column prop="originalPrice" label="原价" width="100" align="center">
        <template #default="scope">
          <span style="color: #909399;">¥{{ scope.row.originalPrice || '0.00' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="promotionPrice" label="促销价" width="100" align="center">
        <template #default="scope">
          <span style="color: #f56c6c; font-weight: bold;">¥{{ scope.row.promotionPrice || '0.00' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠幅度" width="100" align="center">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.originalPrice && scope.row.promotionPrice">
            {{ calculateDiscount(scope.row.originalPrice, scope.row.promotionPrice) }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" min-width="200" align="center" />
      <el-table-column prop="startDate" label="开始时间" width="180" align="center">
        <template #default="scope">
          {{ formatDateTime(scope.row.startDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="endDate" label="结束时间" width="180" align="center">
        <template #default="scope">
          {{ formatDateTime(scope.row.endDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="active" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.active ? 'success' : 'info'">
            {{ scope.row.active ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="currentlyActive" label="当前状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.currentlyActive ? 'success' : 'info'">
            {{ scope.row.currentlyActive ? '进行中' : '未开始/已结束' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">
            <el-icon><Edit /></el-icon>编辑
          </el-button>
          <el-popconfirm
            title="确定删除该促销吗？"
            @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button type="danger" link>
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增促销' : '编辑促销'"
      width="500px"
      @close="handleDialogClose">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="80px">
        <el-form-item label="促销名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入促销名称"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="促销描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入促销描述"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="商品名称" prop="freshProductId">
          <el-select
            v-model="formData.freshProductId"
            placeholder="请选择商品"
            style="width: 100%"
            filterable
            @change="handleProductChange">
            <el-option
              v-for="product in freshProducts"
              :key="product.id"
              :label="product.name"
              :value="product.id">
              <span style="float: left">{{ product.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                ¥{{ product.originalPrice }} | {{ product.category }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="原价" prop="originalPrice">
          <el-input-number
            v-model="formData.originalPrice"
            :min="0"
            :precision="2"
            :step="0.1"
            placeholder="请输入原价"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="促销价" prop="promotionPrice">
          <el-input-number
            v-model="formData.promotionPrice"
            :min="0"
            :precision="2"
            :step="0.1"
            placeholder="请输入促销价"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startDate">
          <el-date-picker
            v-model="formData.startDate"
            type="datetime"
            placeholder="请选择开始时间"
            style="width: 100%"
            value-format="YYYY-MM-DDTHH:mm:ss"
            :disabled-date="disabledStartDate"
            :default-time="new Date(2000, 0, 1, 0, 0, 0)" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endDate">
          <el-date-picker
            v-model="formData.endDate"
            type="datetime"
            placeholder="请选择结束时间"
            style="width: 100%"
            value-format="YYYY-MM-DDTHH:mm:ss"
            :disabled-date="(time) => disabledEndDate(time)"
            :default-time="new Date(2000, 0, 1, 23, 59, 59)" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio v-model="formData.active" :label="true">启用</el-radio>
          <el-radio v-model="formData.active" :label="false">停用</el-radio>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Plus, Edit, Delete, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { get, post } from '@/api/api'
import axios from 'axios'

// 创建API客户端实例
const apiClient = axios.create({
  baseURL: 'http://localhost:8001',
  timeout: 10000
})

// 数据列表
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchText = ref('')

// 生鲜商品数据
const freshProducts = ref([])
const loadingProducts = ref(false)



// 表单相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const submitLoading = ref(false)
const formRef = ref()
const formData = reactive({
  id: null,
  name: '',
  description: '',
  freshProductId: null,
  productName: '',
  originalPrice: 0,
  promotionPrice: 0,
  startDate: null,
  endDate: null,
  active: true
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入促销名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入促销描述', trigger: 'blur' }
  ],
  freshProductId: [
    { required: true, message: '请选择商品', trigger: 'change' }
  ],
  originalPrice: [
    { required: true, message: '请输入原价', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error('原价必须大于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  promotionPrice: [
    { required: true, message: '请输入促销价', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error('促销价必须大于0'))
        } else if (formData.originalPrice && value >= formData.originalPrice) {
          callback(new Error('促销价必须小于原价'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  startDate: [
    { required: true, message: '请选择开始时间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请选择开始时间'))
          return
        }
        const now = new Date()
        const startDate = new Date(value)
        if (startDate < now) {
          callback(new Error('开始时间不能早于当前时间'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  endDate: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请选择结束时间'))
          return
        }
        if (!formData.startDate) {
          callback(new Error('请先选择开始时间'))
          return
        }
        const startDate = new Date(formData.startDate)
        const endDate = new Date(value)
        if (endDate <= startDate) {
          callback(new Error('结束时间必须晚于开始时间'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 获取生鲜商品数据
const fetchFreshProducts = async () => {
  try {
    loadingProducts.value = true
    console.log('开始获取生鲜商品数据...')

    const res = await get('/api/fresh-products')
    console.log('生鲜商品数据响应:', res)

    if (res && res.length > 0) {
      freshProducts.value = res
      console.log('生鲜商品数据加载成功，共', freshProducts.value.length, '个商品')
    } else {
      console.warn('没有获取到生鲜商品数据')
      freshProducts.value = []
    }
  } catch (error) {
    console.error('获取生鲜商品数据失败:', error)
    ElMessage.error('获取商品数据失败: ' + (error.response?.data?.message || error.message))
    freshProducts.value = []
  } finally {
    loadingProducts.value = false
  }
}

// 获取数据列表
const fetchData = async () => {
  loading.value = true
  try {
    const res = await get('/api/promotions')
    console.log('促销列表数据:', res)

    if (res && Array.isArray(res)) {
      // 简单的前端分页处理
      const startIndex = (currentPage.value - 1) * pageSize.value
      const endIndex = startIndex + pageSize.value
      const filteredData = searchText.value
        ? res.filter(item => item.name && item.name.includes(searchText.value))
        : res

      tableData.value = filteredData.slice(startIndex, endIndex)
      total.value = filteredData.length
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}



// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 商品选择变化处理
const handleProductChange = (productId) => {
  console.log('选择的商品ID:', productId)
  const selectedProduct = freshProducts.value.find(p => p.id === productId)
  if (selectedProduct) {
    console.log('选择的商品:', selectedProduct)
    // 自动填充商品信息
    formData.productName = selectedProduct.name
    formData.originalPrice = selectedProduct.originalPrice
    console.log('已自动填充商品信息:', {
      productName: formData.productName,
      originalPrice: formData.originalPrice
    })
  }
}

// 新增
const handleAdd = () => {
  console.log('开始新增促销')
  dialogType.value = 'add'
  resetForm()  // 先重置表单
  // 获取生鲜商品数据
  fetchFreshProducts()
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row) => {
  console.log('开始编辑，原始行数据:', row)

  dialogType.value = 'edit'
  dialogVisible.value = true

  // 深拷贝数据
  Object.assign(formData, {
    ...row
  })

  console.log('编辑表单数据:', JSON.parse(JSON.stringify(formData)))
}

// 删除
const handleDelete = async (id) => {
  try {
    const res = await apiClient.delete(`/api/promotions/${id}`)
    if (res.status === 204 || res.status === 200) {
      ElMessage.success('删除成功')
      if (tableData.value.length === 1 && currentPage.value > 1) {
        currentPage.value--
      }
      fetchData()
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 构造提交数据，匹配后端Promotion实体
        const submitData = {
          name: formData.name,
          description: formData.description,
          freshProductId: formData.freshProductId,
          promotionPrice: formData.promotionPrice,
          startDate: formData.startDate,
          endDate: formData.endDate,
          active: formData.active
        }

        console.log('提交的数据:', submitData)
        console.log('操作类型:', dialogType.value)
        console.log('促销ID:', formData.id)

        let res
        if (dialogType.value === 'add') {
          console.log('执行新增操作...')
          res = await apiClient.post('/api/promotions', submitData)
        } else {
          console.log('执行更新操作...')
          res = await apiClient.put(`/api/promotions/${formData.id}`, submitData)
        }

        console.log('API响应:', res)

        if (res.status === 200 || res.status === 201) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
          dialogVisible.value = false
          await fetchData()
        } else {
          console.error('API调用失败，状态码:', res.status)
          ElMessage.error(`操作失败，状态码: ${res.status}`)
        }
      } catch (error) {
        console.error('操作失败详细信息:', error)
        console.error('错误响应:', error.response?.data)
        ElMessage.error(`操作失败: ${error.response?.data?.message || error.message}`)
      } finally {
        submitLoading.value = false
      }
    } else {
      console.log('表单验证失败')
    }
  })
}



// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    id: null,
    name: '',
    description: '',
    freshProductId: null,
    productName: '',
    originalPrice: 0,
    promotionPrice: 0,
    startDate: null,
    endDate: null,
    active: true
  })
}

// 对话框关闭处理
const handleDialogClose = () => {
  if (dialogType.value === 'add') {
    resetForm()
  }
  // 编辑时不重置表单，保持数据
}

// 同步促销价格
const handleSyncPrices = async () => {
  try {
    loading.value = true
    console.log('开始同步促销价格...')

    const res = await apiClient.post('/api/promotions/actions/sync-prices')
    console.log('同步响应:', res)

    if (res.status === 200) {
      ElMessage.success('促销价格同步成功')
      // 重新获取数据
      await fetchData()
    } else {
      ElMessage.error('促销价格同步失败')
    }
  } catch (error) {
    console.error('同步促销价格失败:', error)
    ElMessage.error(`同步失败: ${error.response?.data || error.message}`)
  } finally {
    loading.value = false
  }
}

// 添加日期处理函数
const formatDateTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
}

// 计算优惠幅度
const calculateDiscount = (originalPrice, promotionPrice) => {
  if (!originalPrice || !promotionPrice || originalPrice <= 0) return '0%'
  const discount = ((originalPrice - promotionPrice) / originalPrice * 100).toFixed(1)
  return `${discount}%`
}

// 开始时间禁用规则
const disabledStartDate = (time) => {
  const now = new Date()
  now.setHours(0, 0, 0, 0)
  return time.getTime() < now.getTime()
}

// 结束时间禁用规则
const disabledEndDate = (time) => {
  if (!formData.startDate) {
    return false
  }
  const startDate = new Date(formData.startDate)
  return time.getTime() <= startDate.getTime()
}

// 初始化
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.promotion-container {
  padding: 20px;
}

.search-wrapper {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>